//
//  questWeekView.m
//  YuTang
//
//  Created by 葛悦彣 on 2024/8/6.
//

#import "questWeekView.h"
#import "myQuestListModel.h"

@interface questWeekView ()<UICollectionViewDelegate,UICollectionViewDataSource,UIAlertViewDelegate>
{
    CGFloat screenWidth;
    CGFloat screenHeight;
    
    int _selectItem;
    int _selectDay;
    NSArray *_weekArray;
    NSMutableArray *_currentMonthArr;
    NSMutableArray *_lastMonthArr;
    NSMutableArray *_nextMonthArr;
    int _nowYear;
    int _nowMonth;
    int _nowDay;
    int _currentYear;
    int _lastYear;
    int _nextYear;
    int _currentMonth;
    int _lastMonth;
    int _nextMonth;
    int _currentWeek;
    int _lastWeek;
    int _nextWeek;
    
    NSMutableArray *_allDayArr;//三个月
    
    UIScrollView *_bgScrollView;
    UIScrollView *_calendarSV;
    UICollectionView *_currentMonthCV;
    UICollectionView *_lastMonthCV;
    UICollectionView *_nextMonthCV;
    
    UICollectionView *_smallCalendar;
    NSMutableArray *_smallDayArr;
    BOOL _isShow;
    BOOL _isTop;
    
    CGFloat _selectOriginY;
    
    UIImageView *_arrowImg;
    NSMutableArray *_allDataArr;
    NSMutableArray *_showArray;
    BOOL _isHistory;
}

@property (nonatomic ,strong) UIView * yearview;
@property (nonatomic ,strong) UILabel * yearLab;
@property (nonatomic ,strong) UIView * weekview;

@end

@implementation questWeekView

+ (instancetype)NewView{
    questWeekView * view = [questWeekView new];
    view.backgroundColor = UIColor.whiteColor;
    [view setupUI];
    return view;
}
- (void)setupUI{
    screenWidth = KSCREEN_WIDTH - kwt(20);
    screenHeight = kwt(50);
    _showArray = [[NSMutableArray alloc] init];
    _allDataArr = [[NSMutableArray alloc] init];
    for (int i = 0; i < 12; i ++) {
        NSDictionary *dic = [NSDictionary dictionaryWithObject:@"12345" forKey:[NSString stringWithFormat:@"13"]];
        [_allDataArr addObject:dic];
    }
    [self addYearView];
    [self addWeekView];
    [self nowDate];
    [self addSmallCalendarView];
    [self showSmallCalendar];
}
- (void)addYearView{
    UIView * yearview = [UIView new];
    self.yearview = yearview;
    [self addSubview:yearview];
    [yearview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.offset(0);
        make.height.offset(kwt(42));
    }];
    
    UILabel * yearLab = [DTKTool labelWithText:@"--年--月" andFont:kCFont(17) andTextColor:KcolorHex(@"#222222")];
    [yearview addSubview:yearLab];
    self.yearLab = yearLab;
    [yearLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.offset(0);
    }];
    
    UIView * line = [UIView new];
    line.backgroundColor = KcolorHex(@"#DBDBDB");
    [yearview addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(0);
        make.left.offset(kwt(14));
        make.right.offset(kwt(-14));
        make.height.offset(0.5);
    }];
    
    UIButton * leftbtn = [UIButton buttonWithType:0];
    leftbtn.addimg([UIImage imageNamed:@"left_black_path"]);
    leftbtn.addTarget(self,@selector(SGYApi));
    [yearview addSubview:leftbtn];
    [leftbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(kwt(14));
        make.width.height.offset(kwt(20));
    }];
    
    UIButton * rightbtn = [UIButton buttonWithType:0];
    rightbtn.addimg([UIImage imageNamed:@"right_black_path"]);
    rightbtn.addTarget(self,@selector(XGYApi));
    [yearview addSubview:rightbtn];
    [rightbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.right.offset(kwt(-14));
        make.width.height.offset(kwt(20));
    }];
    
}

- (void)SGYApi{
    int year = _currentYear;
    int mouth = _currentMonth;
    _selectDay = 1;
    [self getDateWithYear:year WithMonth:mouth-1];
    _selectItem = _currentWeek;
    [self getSmallDayArray];
//    _selectDay = [_smallDayArr[7] componentsSeparatedByString:@"-"].lastObject.intValue;
    [self reloadAllDate];
    CGPoint point = _calendarSV.contentOffset;
    point.x = screenWidth;
    _calendarSV.contentOffset = point;
    
}
- (void)XGYApi{
    int year = _currentYear;
    int mouth = _currentMonth;
    _selectDay = 1;
    [self getDateWithYear:year WithMonth:mouth+1];
    _selectItem = _currentWeek;
    [self getSmallDayArray];
//    _selectDay = [_smallDayArr[7] componentsSeparatedByString:@"-"].lastObject.intValue;
    [self reloadAllDate];
    CGPoint point = _calendarSV.contentOffset;
    point.x = screenWidth;
    _calendarSV.contentOffset = point;
    
}

- (void)addWeekView{
    
    _weekArray = @[@"日",@"一",@"二",@"三",@"四",@"五",@"六"];
    UIView * weekview = [UIView new];
    [self addSubview:weekview];
    self.weekview = weekview;
    [weekview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.equalTo(self.yearview.mas_bottom);
        make.height.offset(kwt(30));
    }];
    UILabel * oldlab;
    for (int i = 0; i < 7; i ++) {
        UILabel *label = [[UILabel alloc] init];
        label.text = [NSString stringWithFormat:@"周%@", _weekArray[i]];
        label.textAlignment = 1;
        label.font = kFont(15);
        label.textColor = KcolorHex(@"#979D9F");
        [weekview addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            if(oldlab){
                make.left.equalTo(oldlab.mas_right);
                make.width.equalTo(oldlab);
            } else {
                make.left.offset(0);
            }
            make.top.bottom.offset(0);
            if(i == 6){
                make.right.offset(0);
            }
        }];
        oldlab = label;
    }
}


//刷新所有的日历(可在此优化)
- (void)reloadAllDate{
   
    
    
    [_smallCalendar reloadData];
}

//初始化周日历
- (void)addSmallCalendarView{
    
    [self getSmallDayArray];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((screenWidth)/7, kwt(50));
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    _smallCalendar = [[UICollectionView alloc] initWithFrame:CGRectMake(0,kwt(72),screenWidth,0) collectionViewLayout:layout];
    _smallCalendar.dataSource = self;
    _smallCalendar.delegate = self;
    _smallCalendar.pagingEnabled = true;
    _smallCalendar.showsHorizontalScrollIndicator = NO;
    _smallCalendar.backgroundColor = [UIColor clearColor];
    [_smallCalendar registerClass:[questWeekViewCell class] forCellWithReuseIdentifier:@"questWeekViewCell"];
    [self addSubview:_smallCalendar];
}

//处理展示周日历时的坐标
- (void)showSmallCalendar{
    
    CGRect rect = _smallCalendar.frame;
    rect.size.height = (screenWidth)/7+1;
    _smallCalendar.frame = rect;
    
    CGPoint point = _smallCalendar.contentOffset;
    point.x = screenWidth;
    _smallCalendar.contentOffset = point;
    
//    CGPoint TVPoint = _bgScrollView.contentOffset;
//    TVPoint.y = (screenWidth)/7*5;
//    _bgScrollView.contentOffset = TVPoint;
//    _arrowImg.image = [UIImage imageNamed:@"slide down icon"];
}

//处理隐藏周日历时的坐标
- (void)hideSmallCalendar{
    
    CGRect rect = _smallCalendar.frame;
    rect.size.height = 0;
    _smallCalendar.frame = rect;
    
//    CGPoint point = _bgScrollView.contentOffset;
//    point.y = 0;
//    _bgScrollView.contentOffset = point;
//    _arrowImg.image = [UIImage imageNamed:@"slide up icon"];
}

//周日历固定21天,月日历统一42天(根据实际的天数显示)
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if (collectionView == _smallCalendar) {
        return 21;
    }else{
        return 7*6;
    }
}

//加载日历的日期
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    questWeekViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"questWeekViewCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    
    cell.time = _smallDayArr[indexPath.item];
    cell.isSeled = (_selectDay  == [_smallDayArr[indexPath.item] componentsSeparatedByString:@"-"].lastObject.intValue);
    cell.state = [self.model stateWithTime:_smallDayArr[indexPath.item]];
    
    return cell;
}

//处理选中日期,
//当前为周日历,并且周日历显示两个月份的日期时(6月,7月),若由6月的日期选到7月的日期,在刷新界面的时候,同时需要将相应的月份更改掉;也许在此做处理.
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *dayString = nil;
    dayString = _smallDayArr[indexPath.item];
    NSArray *array = [dayString componentsSeparatedByString:@"-"];
    int month = [array[1] intValue];
    _selectItem = [array.lastObject intValue];
    _selectDay = _selectItem;
    if (_currentMonth > month) {
        if (_currentMonth == 12) {
            _selectItem = _selectItem + _nextWeek-2;
            [self getDateWithYear:_currentYear WithMonth:_currentMonth+1];
        }else{
            _selectItem = _selectItem + _lastWeek-2;
            [self getDateWithYear:_currentYear WithMonth:_currentMonth-1];
        }
    }else if (_currentMonth == month){
        _selectItem = _selectItem + _currentWeek-2;
    }else{
        if (month == 12) {
            _selectItem = _selectItem + _lastWeek-2;
            [self getDateWithYear:_currentYear WithMonth:_currentMonth-1];
        }else{
            _selectItem = _selectItem + _nextWeek-2;
            [self getDateWithYear:_currentYear WithMonth:_currentMonth+1];
        }
    }
    [self getSmallDayArray];
    
    [_smallCalendar reloadData];
}

//左右切换月份
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    NSString *dayString = nil;
    ///减1周
        if (scrollView.contentOffset.x>=0 && scrollView.contentOffset.x<=10) {
            dayString = _smallDayArr[0];
            NSArray *array = [dayString componentsSeparatedByString:@"-"];
            _selectDay = [[array lastObject] intValue];
            _selectItem = _selectDay;
            _selectItem = _selectItem+(_currentWeek-1);
            int nowMouth = [array[1]  intValue];
            if (nowMouth != _currentMonth) {
                int year = _currentYear;
                int month = _currentMonth;
                [self getDateWithYear:year WithMonth:month-1];
                 //若每次改变月份都要请求新的数据,就在此将旧数据删掉
//                [_allDataArr removeAllObjects];
                _selectItem = _selectItem+(_currentWeek-1);
            }
        }
//        NSLog(@"X = %f,w = %f ,屏幕宽度%f",scrollView.contentOffset.x,screenWidth,KSCREEN_WIDTH);
       ///加1周
        if (scrollView.contentOffset.x>=2*(screenWidth-30) && scrollView.contentOffset.x<=2*(screenWidth+30)) {
            dayString = _smallDayArr[14];
            NSArray *array = [dayString componentsSeparatedByString:@"-"];
            _selectDay = [[array lastObject] intValue];
            _selectItem = _selectDay;
            _selectItem = _selectItem+(_currentWeek-1);
            int nowMouth = [array[1]  intValue];
            if (nowMouth != _currentMonth) {
                int year = _currentYear;
                int month = _currentMonth;
                [self getDateWithYear:year WithMonth:month+1];
                 //若每次改变月份都要请求新的数据,就在此将旧数据删掉
//                [_allDataArr removeAllObjects];
                _selectItem = _selectItem+(_currentWeek-1);
            }
        }
        
        [self getSmallDayArray];
        [self reloadAllDate];
        _smallCalendar.contentOffset = CGPointMake(screenWidth, 0);
    

}


//计算相应的年份
- (int)getYearWithYear:(int)year WithMonth:(int)month{
    
    if (month <= 0) {
        year = year - 1;
    }else if (month >= 13) {
        year = year + 1;
    }
    
    return year;
}

//计算相应的月份
- (int)getMonthWithMonth:(int)month{
    
    if (month <= 0) {
        month = 12;
    }else if(month >= 13){
        month = 1;
    }
    
    return month;
}

//根据日期得到相应的星期
- (int)getWeekWithYear:(int)year WihtMonth:(int)month WithDay:(int)day{
    
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    comps.day = day;
    comps.month = month;
    comps.year = year;
    NSCalendar *calendar = [[NSCalendar alloc]
                            initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *date = [calendar dateFromComponents:comps];
    NSDateComponents *components =
    [calendar components:NSCalendarUnitWeekday fromDate:date];
    int week = (int)[components weekday];
    
    return week;
}

//计算某年某月的日期
- (NSMutableArray *)getDayArrayWithYear:(int)year WithMonth:(int)month{
    
    NSCalendar *calendar = [[NSCalendar alloc]
                            initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM";
    NSString *dayString = [NSString stringWithFormat:@"%d-%d",year,month];
    NSDate *date = [formatter dateFromString:dayString];
    NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    NSMutableArray *dayArray = [[NSMutableArray alloc] init];
    for (int i = 1;i <= range.length; i++) {
        NSString *mouthStr;
        NSString *dayStr;
        if (month<10) {
            mouthStr = [NSString stringWithFormat:@"0%d",month];
        }else{
            mouthStr = [NSString stringWithFormat:@"%d",month];
        }
        if (i<10) {
            dayStr = [NSString stringWithFormat:@"0%d",i];
        }else{
            dayStr = [NSString stringWithFormat:@"%d",i];
        }
        [dayArray addObject:[NSString stringWithFormat:@"%d-%@-%@",year,mouthStr,dayStr]];
    }
    
    return dayArray;
}

//计算当前的日期
- (void)nowDate{
    
    NSDate *now = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy";
    NSString *year = [formatter stringFromDate:now];
    formatter.dateFormat = @"MM";
    NSString *mouth = [formatter stringFromDate:now];
    formatter.dateFormat = @"dd";
    NSString *day = [formatter stringFromDate:now];
    
    _nowYear = [year intValue];
    _nowMonth = [mouth intValue];
    _nowDay = [day intValue];
    _selectDay = _nowDay;
    
    [self getDateWithYear:_nowYear WithMonth:_nowMonth];
    _selectItem = _nowDay + _currentWeek-2;
}

//每次刷新界面时都需要计算年月日星期
- (void)getDateWithYear:(int)year WithMonth:(int)month{
    
    _currentYear = [self getYearWithYear:year WithMonth:month];
    _currentMonth = [self getMonthWithMonth:month];
    _currentWeek = [self getWeekWithYear:_currentYear WihtMonth:_currentMonth WithDay:1];
    _currentMonthArr = [self getDayArrayWithYear:_currentYear WithMonth:_currentMonth];
    self.yearLab.text = [NSString stringWithFormat:@"%d年%d月",_currentYear,_currentMonth];
    
    _lastYear = [self getYearWithYear:_currentYear WithMonth:_currentMonth-1];
    _lastMonth = [self getMonthWithMonth:_currentMonth-1];
    _lastWeek = [self getWeekWithYear:_lastYear WihtMonth:_lastMonth WithDay:1];
    _lastMonthArr = [self getDayArrayWithYear:_lastYear WithMonth:_lastMonth];
    
    _nextYear = [self getYearWithYear:_currentYear WithMonth:_currentMonth+1];
    _nextMonth = [self getMonthWithMonth:_currentMonth+1];
    _nextWeek = [self getWeekWithYear:_nextYear WihtMonth:_nextMonth WithDay:1];
    _nextMonthArr = [self getDayArrayWithYear:_nextYear WithMonth:_nextMonth];
}

//通过当前三个月的日期,计算出周日历的日期(每次计算三周)
- (void)getSmallDayArray{
    
    if (_allDayArr == nil) {
        _allDayArr = [[NSMutableArray alloc] init];
    }else{
        [_allDayArr removeAllObjects];
    }
    
    if (_smallDayArr == nil) {
        _smallDayArr = [[NSMutableArray alloc] init];
    }else{
        [_smallDayArr removeAllObjects];
    }
    _allDayArr = [[NSMutableArray alloc] init];
    [_allDayArr addObjectsFromArray:_lastMonthArr];
    [_allDayArr addObjectsFromArray:_currentMonthArr];
    [_allDayArr addObjectsFromArray:_nextMonthArr];
    
    int week = _selectItem%7;
    //当当前月的1号是周六时,week=0;若week=0,得到的小日历的日期会增加一周
    if (week == 0 && _selectDay == 1) {
        week = 7;
    }
    int first = (int)_lastMonthArr.count-1+_selectItem-_currentWeek+1-week-6;
    for (int i = first; i < first+21; i ++) {
        NSString *dayStr = _allDayArr[i];
        [_smallDayArr addObject:dayStr];
    }
    if(self.openTimeBlock){
        NSString * day = @"";
        for (NSString * dayStr in _smallDayArr) {
            if( [dayStr componentsSeparatedByString:@"-"].lastObject.intValue == _selectDay) {
                day = dayStr;
            }
        }
        ///判断时间
        NSString * startTime = _smallDayArr[7];
        NSString * endTime = _smallDayArr[13];
///
        ///判断当前时间
        NSDate * jtDate = [NSDate br_setYear:[NSDate new].br_year month:[NSDate new].br_month day:[NSDate new].br_day];
        ///开始时间是过去
        if([jtDate compare:[NSDate br_dateFromString:startTime dateFormat:@"yyyy-MM-dd"]] != NSOrderedAscending){
           ///结束时间也在过去
            if([jtDate compare:[NSDate br_dateFromString:endTime dateFormat:@"yyyy-MM-dd"]] != NSOrderedAscending){
                self.openTimeBlock(day, startTime, endTime);
            } else {///结束时间拉到今天
                endTime = [NSDate br_stringFromDate:[NSDate new] dateFormat:@"yyyy-MM-dd"];
                self.openTimeBlock(day, startTime, endTime);
            }
        }else {///直接不传区间
            self.openTimeBlock(day, startTime, endTime);

        }
        
        
    }
    [_smallCalendar reloadData];
}
- (void)setModel:(myQuestTimeListModel *)model{
    _model = model;
    [_smallCalendar reloadData];
}
@end

@interface questWeekViewCell ()
@property (nonatomic ,strong) UILabel * day;
@property (nonatomic ,strong) UIView * bdview;
@end

@implementation questWeekViewCell


-(instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
      
        [self setupUI];
    }
    
    return self;
}
- (void)setupUI{
    UILabel * day = [DTKTool labelWithText:@"-" andFont:kCFont(17) andTextColor:KcolorHex(@"#222222")];
    self.day = day;
    day.textAlignment = NSTextAlignmentCenter;
    [DTKTool YJ:kwt(12) andView:day];
    [self addSubview:day];
    [day mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.offset(kwt(5));
        make.width.height.offset(kwt(24));
    }];
    
    UIView * bdview = [UIView new];
    self.bdview= bdview;
    [DTKTool YJ:kwt(3) andView:bdview];
    [self addSubview:bdview];
    [bdview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(kwt(6));
        make.centerX.offset(0);
        make.bottom.offset(kwt(-10));
    }];
}
- (void)setTime:(NSString *)time{
    NSDate * date = [NSDate br_dateFromString:time dateFormat:@"yyyy-MM-dd"];
    ///判断当前时间
    NSDate * jtDate = [NSDate br_setYear:[NSDate new].br_year month:[NSDate new].br_month day:[NSDate new].br_day];
    
    if([jtDate compare:date] == NSOrderedAscending){
        ///将来
        self.day.text = [NSString stringWithFormat:@"%lu", date.br_day];
        self.day.textColor = KcolorHex(@"#979D9F");
     
    } else if([jtDate compare:date] == NSOrderedSame){
        ///今天
        self.day.text = @"今";
        self.day.textColor = KcolorHex(@"#222222");

    } else {
        ///过去
        self.day.text = [NSString stringWithFormat:@"%lu", date.br_day];
        self.day.textColor = KcolorHex(@"#222222");

    }
    
}
- (void)setIsSeled:(BOOL)isSeled{
    if(isSeled){
        self.day.backgroundColor = KcolorHex(@"#0967FF");
        self.day.textColor = UIColor.whiteColor;
    } else {
        self.day.backgroundColor = UIColor.whiteColor;
    }
}
- (void)setState:(NSInteger)state{
    if(state == 1){
        self.bdview.backgroundColor = KcolorHex(@"#FA8A0C");

    } else if(state == 2){
        self.bdview.backgroundColor = KcolorHex(@"#29B560");

    } else {
        self.bdview.backgroundColor = UIColor.whiteColor;
    }
}
@end
